﻿using Micro.Core.Options;
using Micro.Core.Packages;
using Micro.Core.Reflection;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.AspNetCore.Builder
{
    /// <summary>
    /// <see cref="IApplicationBuilder"/>辅助扩展方法
    /// </summary>
    public static class ApplicationBuilderExtensions
    {
        


        /// <summary>
        /// Micro框架初始化，适用于AspNetCore环境
        /// </summary>
        public static WebApplication UseMicro(this WebApplication app)
        {
            IServiceProvider provider = app.Services;
            ILogger logger = provider.GetLogger("ApplicationBuilderExtensions");
            logger.LogInformation(0, "Micro框架初始化开始");


            Stopwatch watch = Stopwatch.StartNew();
            BasePackage[] packs = provider.GetAllPacks();
            logger.LogInformation($"共有 {packs.Length} 个Pack模块需要初始化");
            foreach (BasePackage pack in packs)
            {
                Type packType = pack.GetType();
                string packName = packType.GetDescription();
                logger.LogInformation($"正在初始化模块 “{packName} ({packType.Name})”");
                pack.UsePack(app);
                logger.LogInformation($"模块 “{packName} ({packType.Name})” 初始化完成\n");
            }
            foreach (BasePackage pack in packs)
            {
                pack.UsePacked(app);
            }

            watch.Stop();
            logger.LogInformation(0, $"Micro框架初始化完成，耗时：{watch.Elapsed}\r\n");

            return app;
        }

        /// <summary>
        /// 添加MVC并Area路由支持
        /// </summary>
        public static IApplicationBuilder UseMvcWithAreaRoute(this IApplicationBuilder app, bool area = true)
        {
            return app.UseMvc(builder =>
            {
                if (area)
                {
                    builder.MapRoute("area", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                }
                builder.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
            });
        }

        /// <summary>
        /// 添加Endpoint并Area路由支持
        /// </summary>
        public static IEndpointRouteBuilder MapControllersWithAreaRoute(this IEndpointRouteBuilder endpoints, bool area = true)
        {
            if (area)
            {
                endpoints.MapControllerRoute(
                    name: "areas-router",
                    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
            }

            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            return endpoints;
        }
        /// <summary>
        /// 设置自定义启动Urls
        /// </summary>
        public static WebApplication UseCustomUrls(this WebApplication app)
        {
            var hostOptions = app.Services.GetService<HostOptions>();
            if (hostOptions.UrlsArray.Any())
                foreach (var url in hostOptions.UrlsArray)
                    app.Urls.Add(url);
            return app;
        }
    }
}
